package ${package}.config.oauth;

import lombok.AllArgsConstructor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;
import org.springframework.security.oauth2.provider.token.store.JwtTokenStore;

/**
 * @author ${author}
 * @date ${date}
 */
@Configuration
@AllArgsConstructor
@EnableResourceServer
public class ResourceServerConfig extends ResourceServerConfigurerAdapter {

    private final OauthProperties oauthProperties;

    private final CustomResourceExceptionHandler customResourceExceptionHandler;

    @Override
    public void configure(ResourceServerSecurityConfigurer resources) {
        resources.resourceId(oauthProperties.getResourceId())
                .tokenStore(tokenStore())
                .authenticationEntryPoint(customResourceExceptionHandler)
                .accessDeniedHandler(customResourceExceptionHandler);
    }

    @Override
    public void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
            .antMatchers("/oauth/**","/doc.html",
            "/v2/api-docs-ext","/swagger-resources",
            "/v2/api-docs","/swagger-ui.html",
            "/swagger-resources/configuration/ui",
            "/swagger-resources/configuration/security",
            "/webjars/**","/favicon.ico","/common/captcha/**")
            .permitAll()
            .and()
            .authorizeRequests()
            .anyRequest()
            .authenticated();
    }

    /**
    * 设置token存储，这一点配置要与授权服务器相一致
    */
    @Bean
    public TokenStore tokenStore() {
        return new JwtTokenStore(accessTokenConverter());
    }

    /**
    * jwt token解析器
    */
    @Bean
    public JwtAccessTokenConverter accessTokenConverter() {
        JwtAccessTokenConverter jwtAccessTokenConverter = new JwtAccessTokenConverter();
        jwtAccessTokenConverter.setSigningKey(oauthProperties.getJwtKey());
        return jwtAccessTokenConverter;
    }
}
